/* lcn/main.c 
 * 
 * This file is part of lcn. 
 * 
 * lcn is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version. 
 * 
 * lcn is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with lcn. If not, see <https://www.gnu.org/licenses/>
 */ 




#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <locale.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/mman.h>

#include <lcn/lcn.h>

int fd;

int init_socket(const char *server_addr, int server_port) {
	struct sockaddr_in addr, server;

	if (unlikely((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)) {
		perror("socket()");

		exit(1);
	}

	memset(&addr, 0, sizeof(struct sockaddr_in));

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port = htons(0);

	if (unlikely(bind(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0)) {
		perror("bind()");

		exit(1);
	}

	memset(&server, 0, sizeof(struct sockaddr_in));

	server.sin_family = AF_INET;
	server.sin_port = htons(server_port);

	if (unlikely(!inet_aton(server_addr, &server.sin_addr))) {
		fprintf(stderr, "invalid ip address. "
				"leave blank if you want to connect the default server. \n");

		exit(1);
	}

	if (unlikely(connect(fd, (struct sockaddr *) &server, sizeof(struct sockaddr_in)) < 0)) {
		perror("connect()");

		exit(1);
	}

	return fd;
}


int main(int argc, char **argv) {
	char buf[PATH_MAX];

	(void) argc;

#ifdef _WIN32
	setlocale(LC_ALL, ".UTF-8");
#else
	setlocale(LC_ALL, "C.UTF-8");
#endif

	init_socket(argv[1] ? argv[1] : "124.223.105.230", LCND_PORT);
	printf("Connected to server. \n");

	for (;;) {
		printf("# ");
		fflush(stdout);

		memset(buf, 0, PATH_MAX);
		read(0, buf, PATH_MAX);

		do_command(buf);
	}

	close(fd);

	return 0;
}

